<template>
  <div class="order">
    <div class="top_bar">
      <van-nav-bar title="买买买！" left-arrow @click-left="$router.back()" />
    </div>
    <div class="address">
      <van-address-list
        v-model="chosenAddressId"
        :disabled-list="address"
        add-button-text="提交订单"
        @add="submit"
        @edit-disabled="goChooseAddress"
      />
    </div>
    <div class="order_goods">
      <van-card
        v-for="item in goods"
        :num="!num ? item.Cartcount : num"
        :price="item.goods_price"
        :title="item.goods_name"
        :thumb="item.goods_big_logo"
        :key="item.goods_id"
      />
    </div>
    <div class="cell">
      <van-cell
        title="商品金额"
        :value="tolalPrice.toFixed(2)"
        size="large"
        class="tolalPrice"
      />
      <van-cell title="运费" value="￥0" size="large" arrow-direction="right" />
      <!-- 优惠券单元格 -->
      <van-coupon-cell
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        @click="showList = true"
      />
      <!-- 优惠券列表 -->
      <van-popup
        v-model="showList"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px"
      >
        <van-coupon-list
          :coupons="coupons"
          :chosen-coupon="chosenCoupon"
          :disabled-coupons="disabledCoupons"
          @change="onChange"
          @exchange="onExchange"
        >
        </van-coupon-list>
      </van-popup>
      <van-cell
        title="合计"
        :value="del_tolalPrice.toFixed(2)"
        size="large"
        class="tolalPrice heji"
      />
    </div>
  </div>
</template>
<script>
export default {
  name: "SubOrder",
  data() {
    return {
      // 商品
      goods: [],
      // 数量
      num: 0,
      // 总价价格
      tolalPrice: 0,
      // 券后价
      del_tolalPrice: 0,
      //   地址
      address: [],
      chosenAddressId: "1",
      //选择优惠卷的索引
      chosenCoupon: -1,
      //可用优惠卷
      coupons: [
        {
          available: 1,
          condition: "无使用门槛\n最多优惠12元",
          reason: "",
          value: 300,
          name: "鹏哥专用优惠券",
          startAt: 1636089689805,
          endAt: 1636989689805,
          valueDesc: "3",
          unitDesc: "元",
        },
        {
          available: 1,
          condition: "最多优惠10元",
          reason: "",
          value: 400,
          name: "大海专用优惠券",
          startAt: 1636079689805,
          endAt: 1636789689805,
          valueDesc: "4",
          unitDesc: "元",
        },
        {
          available: 1,
          condition: "无使用门槛",
          reason: "",
          value: 500,
          name: "AT专用优惠券",
          startAt: 163019689805,
          endAt: 1636589689805,
          valueDesc: "5",
          unitDesc: "元",
        },
      ],
      //不可用优惠卷
      disabledCoupons: [
        {
          available: 1,
          condition: "已过期",
          reason: "",
          value: 500,
          name: "满100减5元",
          startAt: 1633089689805,
          endAt: 1634089689805,
          valueDesc: "5",
          unitDesc: "元",
        },
      ],
      // 优惠卷的显示与隐藏
      showList: false,
    };
  },
  methods: {
    // 获取当前商品商品信息
    getData(id) {
      this.$request.post("/goods/" + id).then(({ data }) => {
        if (data.status == 200) {
          this.goods.push(data.data);
          this.tolalPrice = this.del_tolalPrice =
            this.num * data.data.goods_price;
        }
      });
    },
    // 获取地址
    getAddress(id) {
      this.$request
        .post(
          "/getAddress",
          {
            username: this.userInfo.username,
          },
          {
            headers: {
              token: this.userInfo.token,
            },
          }
        )
        .then(({ data }) => {
          if (data.data.length == 0) {
            this.$router.push("/address");
            return;
          }
          let item = {};
          if (id) {
            item = data.data.filter((items) => items.Addressid == id)[0];
          } else {
            item =
              data.data.filter((item) => item.Isdefault).length == 0
                ? data.data[0]
                : data.data.filter((item) => item.Isdefault)[0];
          }
          const obj = {
            id: 1,
            name: item.Name,
            tel: item.Phonenum,
            address: item.Address + item.AddressDetail,
            isDefault: item.Isdefault,
            Addressid: item.Addressid,
          };
          this.address.push(obj);
        });
    },
    //提交订单
    async submit() {
      const goods = this.goods.map((item) => {
        return {
          GoodId: item.goods_id,
          Cartcount: !this.num  ? item.Cartcount : this.num,
        };
      });
      const { data } = await this.$request.post(
        "/createOrder",
        {
          username: this.userInfo.username,
          addressId: this.address[0].Addressid,
          goods: goods,
          totalMoney: this.del_tolalPrice,
        },
        {
          headers: {
            token: this.userInfo.token,
          },
        }
      );
      if (data.status != 200) return;
      if (this.$route.query.flag == "cart"|| this.$route.query.id) {
        // 删选购物车已提交商品
        let ids = [];
        const data = await this.cartlist.forEach((item) => {
          if (item.is_select) {
            ids.push(item.goods_id);
          }
        });
        this.$request.post(
          "/delFromCart",
          { username: this.userInfo.username, delIds: ids },
          {
            headers: {
              token: this.userInfo.token,
            },
          }
        );
        this.$store.commit("cart/removeFromCart", ids);
      }
      this.$toast.success("提交订单成功");
      setTimeout(() => {
        this.$router.replace("/order");
      }, 1000);
    },
    //	优惠券切换回调
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;
      if (index >= 0) {
        this.del_tolalPrice = this.tolalPrice - this.coupons[index].valueDesc;
      }
    },
    //	兑换优惠券回调
    onExchange(code) {
      this.coupons.push(coupon);
    },
    // 选择地址
    goChooseAddress() {
      this.$router.push({
        name: "Address",
        query: { flag: "SubOrder" },
      });
    },
  },
  computed: {
    // 计算总价
    calculation() {
      return this.cartlist
        .filter((item) => item.is_select)
        .reduce((pre, item) => {
          return pre + item.goods_price * item.Cartcount;
        }, 0);
    },
    // 获取本地购物车数据
    cartlist() {
      return this.$store.state.cart.cartlist;
    },
    // 获取本地用户信息
    userInfo() {
      return this.$store.state.user.userInfo;
    },
  },
  created() {
    // 获取地址
    if (this.$route.query.id) {
      // 选择地址
      this.getAddress(this.$route.query.id);
    } else {
      // 选择默认地址
      this.getAddress();
    }
    // 获取订单数据
    if (this.$route.query.goodId || this.$route.query.id) {
      if (this.$route.query.goodId) {
        localStorage.setItem("good", JSON.stringify(this.$route.query));
      }
      const good = JSON.parse(localStorage.getItem("good"));
      this.num = good.num;
      if (good.goodId) {
        this.getData(good.goodId);
      }else{
        this.goods= JSON.parse(localStorage.getItem("good"))
         this.tolalPrice = this.del_tolalPrice = this.calculation;
      }
    } else {
      this.goods = this.cartlist.filter((item) => item.is_select);
      this.tolalPrice = this.del_tolalPrice = this.calculation;
       localStorage.setItem("good", JSON.stringify(this.goods));
    }
  },
  mounted() {
    // 进入该组件隐藏底部bar
    this.$parent.isShowbar = false;
  },
  destroyed() {
    // 退出该组件显示底部bar
    this.$parent.isShowbar = true;
  },
};
</script>
<style scoped lang="scss">
.order {
  padding-bottom: 50px;
}
.top_bar {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 9999;
}
.address {
  margin-top: 46px;
}
.van-address-list {
  padding: 3px;
  border-bottom: 2px solid red;

  .van-address-item {
    margin-bottom: 0px;
  }
}
.order_goods {
  margin-top: 10px;
}
.van-card__price {
  color: #f00;
  .van-card__price-currency {
    font-size: 14px;
  }
  .van-card__price-integer {
    font-size: 25px;
  }
}
.cell {
  margin-top: 30px;
  .tolalPrice {
    .van-cell__value {
      span {
        font-weight: 500;
        font-size: 20px;
        &::before {
          content: "¥";
          font-size: 20px;
        }
      }
    }
  }
  .heji {
    .van-cell__value {
      color: #f00;
    }
  }
  .van-cell__title {
    font-size: 14px;
  }
}
</style>